package com.ruoyi.wx.controller;

import com.github.wxpay.sdk.WXPayUtil;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.utils.ConvertUtil;
import com.ruoyi.wx.service.WXPayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * @author X
 * @version 1.0
 * @ClassName WXPayController
 * @description
 * @date 2020/11/10
 **/
@RestController
@RequestMapping("/wx/pay")
public class WXPayController {

    @Autowired
    private WXPayService wxPayService;

    @PostMapping("/nativePay")
    public AjaxResult nativePay(@RequestBody Map<String, String> parameterMap, HttpServletRequest request) {
        Map map = wxPayService.nativePay(parameterMap, request);
        return AjaxResult.success(map);
    }

    @GetMapping("/getQR")
    public void getQR(@RequestParam String codeUrl, HttpServletResponse response) throws Exception {
        BitMatrix qr = wxPayService.getQR(codeUrl);
        ServletOutputStream outputStream = response.getOutputStream();
        MatrixToImageWriter.writeToStream(qr, "png", outputStream);
    }

    @RequestMapping("/notify")
    public void notifyLogic(HttpServletRequest request, HttpServletResponse response) {
        try {
            //输入流转换为字符串
            String xml = ConvertUtil.convertToString(request.getInputStream());
            System.out.println(xml);

            //基于微信发送的通知内容,完成后续的业务逻辑处理
            Map<String, String> map = WXPayUtil.xmlToMap(xml);
            if ("SUCCESS".equals(map.get("result_code"))) {

                //查询订单
                Map result = wxPayService.queryOrder(map.get("out_trade_no"));
                System.out.println("查询订单结果:" + result);
                //获取自定义参数
                String attach = map.get("attach");

                if ("SUCCESS".equals(result.get("result_code"))) {

                    //将商人支付状态保存数据库

                } else {
                    //输出错误原因
                    System.out.println(map.get("err_code_des"));
                }

            } else {
                //输出错误原因
                System.out.println(map.get("err_code_des"));
            }

            //给微信一个结果通知
            response.setContentType("text/xml");
            String data = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
            response.getWriter().write(data);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
